package com.tjp.eight.ui.fragment.search;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.thirdparty.V;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;
import com.tjp.eight.R;
import com.tjp.eight.comment.AppManager;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.ui.fragment.rank.RankAdapter;
import com.tjp.eight.ui.fragment.tabFind.FindResultModel;
import com.tjp.eight.utils.ActivityUtils;
import com.tjp.eight.utils.AnimationUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.rcview.EndlessRecyclerOnScrollListener;
import com.tjp.eight.views.rcview.HeaderViewRecyclerAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Created by Administrator on 2017/2/27.
 */
public class FragmentSearch extends BaseFragment<SearchPresenter> implements SearchsView, View.OnClickListener {
    private static String TAG = FragmentSearch.class.getSimpleName();
    private RecyclerView rv_search;
    private HeaderViewRecyclerAdapter headerViewRecyclerAdapter;
    private View footView;
    private RankAdapter rankAdapter;
    private LinearLayout ll_search_tips;
    private LinearLayout ll_search_container;
    private TextView tv_hot;
    private TextView tv_qiqu;
    private TextView tv_fun;
    private TextView tv_dog;
    private TextView tv_gx;
    private TextView tv_life;
    private TextView tv_search;
    public String wd = "";
    private ImageView iv_search_clear;
    private ImageView iv_voice_search;
    private EditText et_search;
    RelativeLayout rl_head_left;
    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<>();

    int ret = 0; // 函数调用返回值
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    @Override
    protected SearchPresenter createPresenter() {
        return new SearchPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.fragment_search, container, false);
        }
        initViews();
        getPermission();
        return contentView;
    }

    boolean getPermission() {
        boolean isPer = true;
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, 2000);
                isPer = false;
            }
        }

        return isPer;
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                //  showTip("初始化失败，错误码：" + code);
            }
        }
    };

    private void initViews() {
        rv_search = (RecyclerView) contentView.findViewById(R.id.rv_search);
        rv_search.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        rankAdapter = new RankAdapter(getActivity());
        rankAdapter.setNoRank(false);
        headerViewRecyclerAdapter = new HeaderViewRecyclerAdapter(rankAdapter);
        rankAdapter.setItemOnClick(new RankAdapter.RankItemOnClick() {
            @Override
            public void itemClick(String cid) {
                ActivityUtils.startDetails(getActivity(), cid);
            }
        });
        footView = LayoutInflater.from(getContext()).inflate(R.layout.swipe_refresh_footer, rv_search, false);
        rv_search.setAdapter(headerViewRecyclerAdapter);

        ll_search_container = (LinearLayout) contentView.findViewById(R.id.ll_search_container);
        ll_search_tips = (LinearLayout) contentView.findViewById(R.id.ll_search_tips);
        ll_search_container.setVisibility(View.GONE);
        ll_search_tips.setVisibility(View.VISIBLE);
        tv_hot = (TextView) contentView.findViewById(R.id.tv_hot);
        tv_qiqu = (TextView) contentView.findViewById(R.id.tv_qiqu);
        tv_fun = (TextView) contentView.findViewById(R.id.tv_fun);
        tv_dog = (TextView) contentView.findViewById(R.id.tv_dog);
        tv_gx = (TextView) contentView.findViewById(R.id.tv_gx);
        tv_life = (TextView) contentView.findViewById(R.id.tv_life);
        tv_search = (TextView) contentView.findViewById(R.id.tv_search);
        tv_hot.setOnClickListener(this);
        tv_qiqu.setOnClickListener(this);
        tv_fun.setOnClickListener(this);
        tv_dog.setOnClickListener(this);
        tv_gx.setOnClickListener(this);
        tv_life.setOnClickListener(this);
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isNullOrEmpty(et_search.getText().toString())){
                    wd = et_search.getText().toString();
                    presenter.loadData(getPjson(wd));
                }
            }
        });
        mIat = SpeechRecognizer.createRecognizer(getActivity(), mInitListener);

        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(getActivity(), mInitListener);


        rl_head_left = (RelativeLayout) contentView.findViewById(R.id.rl_head_left);
        rl_head_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getAppManager().finishActivity(getActivity());
            }
        });
        iv_search_clear = (ImageView) contentView.findViewById(R.id.iv_search_clear);
        iv_voice_search = (ImageView) contentView.findViewById(R.id.iv_voice_search);
        iv_voice_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!getPermission()) {
                    return;
                }
                // 移动数据分析，收集开始听写事件
                FlowerCollector.onEvent(getActivity(), "iat_recognize");

                et_search.setText(null);// 清空显示内容
                mIatResults.clear();
                // 设置参数
                setParam();
                boolean isShowDialog = true;
                if (isShowDialog) {
                    mIatDialog.setListener(mRecognizerDialogListener);
                    mIatDialog.show();
                    // showTip(getString(R.string.text_begin));
                } else {
                    ret = mIat.startListening(mRecognizerListener);
                    if (ret != ErrorCode.SUCCESS) {
                        // showTip("听写失败,错误码：" + ret);
                    } else {
                        //showTip(getString(R.string.text_begin));
                    }
                }
            }
        });
        iv_search_clear.setVisibility(View.INVISIBLE);
        iv_search_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_search.setText("");
                if (ll_search_container.getVisibility() == View.VISIBLE) {
                    AnimationUtils.alphaViewGone(ll_search_container);
                }
                if (ll_search_tips.getVisibility() == View.GONE) {
                    AnimationUtils.alphaViewVisible(ll_search_tips);
                }
            }
        });
        et_search = (EditText) contentView.findViewById(R.id.et_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ("".equals(s.toString())) {
                    iv_search_clear.setVisibility(View.INVISIBLE);
                } else {
                    iv_search_clear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results);
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
            // showTip(error.getPlainDescription(true));
        }

    };
    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // showTip("开始说话");
        }

        @Override
        public void onError(SpeechError error) {
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
            // showTip(error.getPlainDescription(true));
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            //  showTip("结束说话");
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            // Log.d(TAG, results.getResultString());
            printResult(results);

            if (isLast) {
            }
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
//            showTip("当前正在说话，音量大小：" + volume);
//            Log.d(TAG, "返回音频数据："+data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }

        et_search.setText(resultBuffer.toString());
        et_search.setSelection(et_search.length());
        wd = et_search.getText().toString();
        if (!StringUtils.isNullOrEmpty(wd))
            presenter.loadData(getPjson(wd));
    }

    /**
     * 参数设置
     */
    public void setParam() {
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        String lag = "mandarin";
        if (lag.equals("en_us")) {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        } else {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);
        }

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, /**mSharedPreferences.getString("iat_vadbos_preference", "4000")**/"4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, /**mSharedPreferences.getString("iat_vadeos_preference", "1000")**/"1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, /**mSharedPreferences.getString("iat_punc_preference", "1")**/"0");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
    }

    @Override
    public void onResume() {
        // 开放统计 移动数据统计分析
        FlowerCollector.onResume(getActivity());
        FlowerCollector.onPageStart(TAG);
        super.onResume();
    }

    @Override
    public void onPause() {
        // 开放统计 移动数据统计分析
        FlowerCollector.onPageEnd(TAG);
        FlowerCollector.onPause(getActivity());
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mIat) {
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_hot:
                wd = tv_hot.getText().toString();
                break;
            case R.id.tv_qiqu:
                wd = tv_qiqu.getText().toString();
                break;
            case R.id.tv_fun:
                wd = tv_fun.getText().toString();
                break;
            case R.id.tv_dog:
                wd = tv_dog.getText().toString();
                break;
            case R.id.tv_gx:
                wd = tv_gx.getText().toString();
                break;
            case R.id.tv_life:
                wd = tv_life.getText().toString();
                break;
        }
        hideKeyboard();
        et_search.setText(wd);
        et_search.setSelection(et_search.length());
        presenter.loadData(getPjson(wd));
    }

    String getPjson(String wd) {
        SearchePModel model = new SearchePModel();
        model.wd = wd;
        return new Gson().toJson(model);
    }
    private void hideKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void loadsuccess(FindResultModel model) {
        hideKeyboard();
        if (model != null) {
            if (model.data != null && !model.data.isEmpty()) {
                rankAdapter.addForSearche(model.data);
                if (ll_search_tips.getVisibility() == View.VISIBLE) {
                    AnimationUtils.alphaViewGone(ll_search_tips);
                }
                if (ll_search_container.getVisibility() == View.GONE) {
                    AnimationUtils.alphaViewVisible(ll_search_container);
                }

            } else {
                if (ll_search_container.getVisibility() == View.VISIBLE) {
                    AnimationUtils.alphaViewGone(ll_search_container);
                }
                if (ll_search_tips.getVisibility() == View.GONE) {
                    AnimationUtils.alphaViewVisible(ll_search_tips);
                }
                ToatUtils.toastSuccess(getContext(),"什么也没有搜到啊~~~");
            }
        }
    }

    @Override
    public void loadfail(String msg) {

    }
}
